﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using RHD.Common.Web.Components.Form;

namespace RHD.Common.Web.Components {
	public static class FormExtension {
		public static MvcHtmlString Form(this HtmlHelper htmlHelper, string id, Action<FormItems> itemsHandle, Action<FormBuilder> optionsHandle = null, object htmlAttributes = null) {
			FormItems items = new FormItems();
			if (itemsHandle != null)
				itemsHandle(items);

			FormBuilder options = new FormBuilder();
			if (optionsHandle != null)
				optionsHandle(options);

			TagBuilder form = GetForm(id, items, options);

			if (htmlAttributes != null)
				form.MergeAttributes<string, object>(new RouteValueDictionary(htmlAttributes));
			
			return MvcHtmlString.Create(form.ToString());
		}

		private static TagBuilder GetForm(string id, FormItems items, FormBuilder options) {
			TagBuilder form = new TagBuilder("div");
			form.GenerateId(id);
			form.AddCssClass("form-horizontal");

			foreach (FormItemBuilder item in items.GetItems()) {
				TagBuilder group = new TagBuilder("div");
				group.AddCssClass("form-group");

				TagBuilder label = new TagBuilder("label");
				label.AddCssClass("col-lg-4 control-label");
				label.SetInnerText(item.label);
				label.Attributes["title"] = item.tooltip;

				TagBuilder controls = new TagBuilder("div");
				controls.AddCssClass("col-lg-8");
				controls.InnerHtml = item.html;

				group.InnerHtml = label.ToString() + controls.ToString();
				form.InnerHtml += group.ToString();
			}

			return form;
		}
	}
}